interface TreeNode {
  [key: string]: any;
  children?: TreeNode[];
}

/**
 * 将树形结构转换为列表
 * @param tree 树形结构数据
 * @param idValue 父节点ID值
 * @param childrenField 子节点字段名 (默认 'children')
 * @param idField ID字段名 (默认 'id')
 * @param parentIdField 父ID字段名 (默认 'parentId')
 * @returns 转换后的列表
 */
export function treeToList<T extends TreeNode>(
  tree: T[] = [],
  idValue: any = null,
  childrenField: string = 'children',
  idField: string = 'id',
  parentIdField: string = 'parentId'
): T[] {
  const list: T[] = [];
  
  for (let i = 0, j = tree.length; i < j; i++) {
    // 使用类型断言确保访问安全
    const d = tree[i] as Record<string, any>;
    const id = d[idField];
    
    // 如果列表中不存在当前节点，则添加
    if (!list.some(l => (l as Record<string, any>)[idField] === id)) {
      // 创建一个新对象以避免修改原始数据
      const node = {...d} as T;
      
      // 设置父节点ID
      if (parentIdField) {
        (node as Record<string, any>)[parentIdField] = idValue;
      }
      
      list.push(node);
    } else {
      // 如果节点已存在，只更新父ID字段
      const existingNode = list.find(l => (l as Record<string, any>)[idField] === id);
      if (existingNode && parentIdField) {
        (existingNode as Record<string, any>)[parentIdField] = idValue;
      }
    }
    
    // 递归处理子节点
    const children = d[childrenField] as T[] | undefined;
    if (children && children.length > 0) {
      const childList = treeToList(
        children, 
        id, 
        childrenField, 
        idField, 
        parentIdField
      );
      
      // 添加子节点到列表
      for (const item of childList) {
        if (!list.some(l => (l as Record<string, any>)[idField] === (item as Record<string, any>)[idField])) {
          list.push(item);
        }
      }
    }
  }
  
  return list;
}
/**
 * 将列表转换为树形结构
 * @param list 列表数据
 * @param root 根节点 (可选)
 * @param idField ID字段名 (默认 'id')
 * @param parentIdField 父ID字段名 (默认 'parentId')
 * @returns 转换后的树形结构
 */
export function listToTree<T extends TreeNode>(
  list: T[] = [],
  root: T | null = null,
  idField: string = 'id',
  parentIdField: string = 'parentId'
): T[] {
  const tree: T[] = [];
  const hash: Record<string | number, T> = {};
  const childrenField = 'children';
  
  // 创建哈希映射
  for (let i = 0, l = list.length; i < l; i++) {
    const d = list[i];
    hash[d[idField]] = d;
  }

  // 构建树结构
  for (let i = 0, l = list.length; i < l; i++) {
    const d = list[i];
    const parentID = d[parentIdField];
    
    // 根节点处理
    if (parentID === '' || parentID === 0 || parentID === null) {
      tree.push(d);
      continue;
    }

    // 查找父节点
    const parent = hash[parentID];
    if (!parent) {
      tree.push(d);
      continue;
    }

    // 添加子节点
    let children = parent[childrenField] as T[];
    if (!children) {
      children = [];
      parent[childrenField] = children;
    }
    children.push(d);
  }

  // 处理自定义根节点
  if (root) {
    root[childrenField] = tree;
    return [root];
  }

  return tree;
}

/**
 * 获取节点的所有父节点
 * @param list 节点列表
 * @param idValue 目标节点ID
 * @param idField ID字段名 (默认 'id')
 * @param parentIdField 父ID字段名 (默认 'parentId')
 * @param includeSelf 是否包含自身 (默认 false)
 * @returns 父节点列表
 */
export function getListParents<T extends TreeNode>(
  list: T[] = [],
  idValue: any,
  idField: string = 'id',
  parentIdField: string = 'parentId',
  includeSelf: boolean = false
): T[] {
  const parents: T[] = [];
  const self = list.find(o => o[idField] === idValue);
  
  if (!self) {
    return parents;
  }

  // 包含自身
  if (includeSelf) {
    parents.unshift(self);
  }

  // 递归查找父节点
  let parent = list.find(o => o[idField] === self[parentIdField]);
  while (parent && parent[idField] > 0) {
    parents.unshift(parent);
    parent = list.find(o => o[idField] === parent![parentIdField]);
  }
  
  return parents;
}

/**
 * 在树中获取节点的所有父节点
 * @param tree 树形结构数据
 * @param idValue 目标节点ID
 * @param childrenField 子节点字段名 (默认 'children')
 * @param idField ID字段名 (默认 'id')
 * @param parentIdField 父ID字段名 (默认 'parentId')
 * @param parentIdValue 父节点ID值 (默认 0)
 * @returns 父节点列表
 */
export function getTreeParents<T extends TreeNode>(
  tree: T[] = [],
  idValue: any,
  childrenField: string = 'children',
  idField: string = 'id',
  parentIdField: string = 'parentId',
  parentIdValue: any = 0
): T[] {
  const list = treeToList(
    tree, 
    parentIdValue, 
    childrenField, 
    idField, 
    parentIdField
  );
  
  return getListParents(
    list, 
    idValue, 
    idField, 
    parentIdField
  );
}

/**
 * 在树中获取节点的所有父节点（包含自身）
 * @param tree 树形结构数据
 * @param idValue 目标节点ID
 * @param childrenField 子节点字段名 (默认 'children')
 * @param idField ID字段名 (默认 'id')
 * @param parentIdField 父ID字段名 (默认 'parentId')
 * @param parentIdValue 父节点ID值 (默认 0)
 * @returns 父节点列表（包含自身）
 */
export function getTreeParentsWithSelf<T extends TreeNode>(
  tree: T[] = [],
  idValue: any,
  childrenField: string = 'children',
  idField: string = 'id',
  parentIdField: string = 'parentId',
  parentIdValue: any = 0
): T[] {
  const list = treeToList(
    tree, 
    parentIdValue, 
    childrenField, 
    idField, 
    parentIdField
  );
  
  return getListParents(
    list, 
    idValue, 
    idField, 
    parentIdField, 
    true
  );
}